import axios from 'axios';
import Qs from 'qs';
import { Message } from 'element-ui';
import router from '@/router';
import store from '@/store/index.js';
import Common from '@/js/common.js';

const instance = axios.create({
  baseURL: process.env.BASE_URL,
  params: {},
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  },
  transformResponse: [function (data) {
    return data;
  }],
  paramsSerializer: function (params) {
    return Qs.stringify(params, { arrayFormat: 'brackets' });
  },
  withCredentials: false, // default
  responseType: 'json', // default
  maxContentLength: 2000,
  maxRedirects: 5, // default
  validateStatus: function (status) {
    return status === 200;
    // return status >= 200 && status < 500;
  }
});

// request 请求拦截器
instance.interceptors.request.use(
  config => {
    const accountDataInfo = Common.getCookie('accountDataInfo') && JSON.parse(Common.getCookie('accountDataInfo'))
    config.headers.token = sessionStorage.token || sessionStorage._token;
    config.headers.Authorization = sessionStorage.token || accountDataInfo.token;
    if (config['headers']['Content-Type'] === 'application/x-www-form-urlencoded') {
      config['data'] = Qs.stringify(config['data']);
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

let errorCount = 0;
/**
 * 封装请求方法
 * @param options, 配置参数
 * @param obj, 回调方法和其他参数
 * @returns {Promise<any>}
 */
const fetch = (options, obj) => {
  let {
    success,
    error,
    showMsg
  } = obj;
  return new Promise((resolve, reject) => {
    instance(options).then((res) => {
      let resContent = {};
      try {
        resContent = res.data ? JSON.parse(res.data) : {};
      } catch (e) {
        resContent = res.data || {};
      }
      let { code, data, msg, status } = resContent;
      status = status || {};
      code = code || code === 0 ? code : status.code;
      msg = msg || status.msg;
      if (code === 200) {
        if (success) {
          success(data, resContent);
        } else {
          resolve(resContent)
        }
      } else if (code === 304 || code === 305 || code === 306) {
        if (!errorCount) {
          errorCount++;
          Message.error('登录失效，请重新登录');
          setTimeout(() => {
            store.dispatch('saveData', {
              key: 'getPermission',
              data: false
            });
            store.dispatch('saveData', {
              key: 'permissionMenu',
              data: []
            });
            store.dispatch('saveData', {
              key: 'realMenu',
              data: []
            });
            sessionStorage.clear();
            Common.delCookie('accountDataInfo')
            router.replace({
              name: 'login'
            });
            errorCount = 0;
          }, 1000);
        }
      } else {
        if (error) {
          error(data, resContent);
        }
        if (msg && !(showMsg === 'no')) {
          Message({ // code !== 200的错误信息提示
            message: msg,
            type: 'error'
          });
          reject(resContent)
        }
      }
    }).catch((err) => {
      let resContent = err.response && err.response.data;
      if (error) {
        error(resContent);
      }
      let msg = resContent && resContent.msg ? resContent.msg : '请求错误';
      Message.error(msg);
      reject(err);
    });
  });
};

const POST = (url, obj) => {
  let {
    params,
    config
  } = obj;
  url = obj.url || url;
  config = config || {};
  return fetch({
    method: 'post',
    url: url,
    data: params || {},
    ...config
  }, obj);
};
const GET = (url, obj) => {
  let {
    params,
    config
  } = obj;
  url = obj.url || url;
  config = config || {};
  return fetch({
    method: 'get',
    url: url,
    params: params || {},
    ...config
  }, obj);
};

export { POST, GET };
